<?php

/**
 *	frontend social login module
 *	gigya (gigya.com) based frontend module that enables a user to login with one of his/her social accounts
 *	facebook / twitter / google / yahoo ..
 *
 * 	the class is documented in the file itself. if you find any bugs help us out and report them. 
 * 	if you report a bug, make sure you give us enough information (include your code).
 *
 *	@copyright		oneDot only <we@onedotonly.be>
 * 	@copyright		Copyright (c) 2010, oneDot only. All rights reserved.
 * 	@license		BSD License
 *
 *	@author			pieter van peteghem <pieter@onedotonly.be>
 */
 
 
class SocialGigya extends MOD {


	/**
	 *	output function
	 *	module builder (add classes / define action / render javascript)
	 */
	function output() {
	
		$extras		= array(
			"containerId" => "gigya-" . $this->action
		);
		
		$this->vars = (object) array_merge( (array) json_decode( engine_get( 'gigya.connect' )), (array) $this->vars, (array) $extras );
		
		$result = $this->{ "filter_" . $this->action }();	
		$this->addclass( $this->action );
			
		return $this->parse( $result ) . $this->render_js();
	}
	
	
	function filter_login() {
		
		//print_r( $_SERVER );
		
		if( !$this->vars->redirectURL )
			$this->vars->redirectURL = $_SERVER[ 'REQUEST_URI' ];
			
		$this->js = "
			var mod = new SocialGigya( " . json_encode( (array) $this->vars ) . " );
			mod.login();
		";
		
		
	
	}
	
	
	function ajax_setUser() {
		global $DB;
	
		$user		= (array) $this->vars->user;
		foreach( $user as $key => $value ) {
			
			$key	= explode( '.', $key );
			if( count( $key ) > 1 )
				$newbie[ 'meta' ][ array_pop( $key ) ] = $value;
			else
				$newbie[ array_pop( $key ) ] = $value;
		}
		
		$new_login = 0;
		
		if(( $uid = $DB->get( 'user', 'user = "' . $newbie[ 'user' ] . '"' )) && !empty( $newbie[ 'user' ])) {

			$_SESSION[ 'uid' ] = $uid[ 'ID' ];
			$update =  array( 'llog' => date( 'Y-m-d H:i:s' ), 'ip' => $_SERVER[ 'REMOTE_ADDR' ], 'meta' => $newbie[ 'meta' ] );
			$DB->update( 'user', array( 'ID' => $_SESSION[ 'uid' ] ), $update );
			
			$_SESSION[ 'gigyauid' ] = $this->vars->gigyauid;
		
		} else if (!empty( $newbie[ 'user' ] )) {

			$uid = $DB->set( 'user', $newbie );
			$_SESSION[ 'uid' ] = $uid;
			$_SESSION[ 'gigyauid' ] = $this->vars->gigyauid;
		
		} else {
		
			//unset( $_SESSION[ 'uid' ] );
		}
		
		$vars = array_merge( (array) $this->vars->user, array( 'redirectURL' => $_SERVER[ 'REQUEST_URI' ], 'newbie' => $new_login, 'userid' =>  $_SESSION[ 'uid' ] ));
		
		return json_encode( $vars );
	}
	
	
	function ajax_logout() {
		
		unset( $_SESSION[ 'uid' ] );
		
		$vars = array_merge( (array) $this->vars->user, array( 'redirectURL' => $_SERVER[ 'HTTP_REFERER' ] ));
		return json_encode( $vars );
		
	}
	
	

}

